{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "8dd22323",
      "metadata": {},
      "source": [
        "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mongodb-developer/GenAI-Showcase/blob/main/notebooks/evals/gemini-embeddings-eval.ipynb)\n",
        "\n",
        "[![View Article](https://img.shields.io/badge/View%20Article-blue)](https://www.mongodb.com/company/blog/technical/how-choose-best-embedding-model-for-your-llm-application/?utm_campaign=devrel&utm_source=cross-post&utm_medium=organic_social&utm_content=https%3A%2F%2Fgithub.com%2Fmongodb-developer%2FGenAI-Showcase&utm_term=apoorva.joshi)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "39b4d49e-31a1-4093-9255-9cb8e6f96b0d",
      "metadata": {
        "tags": []
      },
      "source": [
        "# How to choose the right embedding model for your RAG application\n",
        "\n",
        "This notebook evaluates the [gemini-embedding-001](https://ai.google.dev/gemini-api/docs/embeddings) model.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f3a115b9-68e5-44f7-9ea7-fff56bc9ee59",
      "metadata": {},
      "source": [
        "## Step 1: Install required libraries\n",
        "\n",
        "- **datasets**: Python library to get access to datasets available on Hugging Face Hub\n",
        "- **google-genai**: Google’s GenAI Python SDK\n",
        "- **numpy**: Python library that provides tools to perform mathematical operations on arrays\n",
        "- **pandas**: Python library for data analysis, exploration and manipulation\n",
        "- **tdqm**: Python module to show a progress meter for loops\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 25,
      "id": "a999fe13-3eee-4fd8-a9fd-0f2f37171ed3",
      "metadata": {
        "tags": []
      },
      "outputs": [],
      "source": [
        "! pip install -qU datasets google-genai numpy pandas tqdm"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "87bd8b3e-984b-4dff-bd7f-615e577a9ef8",
      "metadata": {},
      "source": [
        "## Step 2: Setup pre-requisites\n",
        "\n",
        "Set the Gemini API key as an environment variable, and initialize the Gemini client.\n",
        "\n",
        "Steps to obtain a Gemini API Key can be found [here](https://aistudio.google.com/app/apikey)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 26,
      "id": "f62e40d3-852c-4abf-9151-875a1d32e93e",
      "metadata": {},
      "outputs": [],
      "source": [
        "import getpass\n",
        "import os\n",
        "\n",
        "from google import genai"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 27,
      "id": "a8e8bcde-c242-4641-a7c8-5f69c60d021e",
      "metadata": {},
      "outputs": [
        {
          "name": "stdin",
          "output_type": "stream",
          "text": [
            "Gemini API Key: ········\n"
          ]
        }
      ],
      "source": [
        "os.environ[\"GEMINI_API_KEY\"] = getpass.getpass(\"Gemini API Key:\")\n",
        "gemini_client = genai.Client()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b5a99a68-a7d2-4657-8f05-ea75f19b6748",
      "metadata": {},
      "source": [
        "## Step 3: Download the evaluation dataset\n",
        "\n",
        "We will use MongoDB's [cosmopedia-wikihow-chunked](https://huggingface.co/datasets/MongoDB/cosmopedia-wikihow-chunked) dataset, which has chunked versions of WikiHow articles from the [Cosmopedia](https://huggingface.co/datasets/HuggingFaceTB/cosmopedia) dataset released by Hugging Face. The dataset is pretty large, so we will only grab the first 2k records for testing.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 28,
      "id": "7862e2db-fec8-4294-ad75-9753e69adc1a",
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "from datasets import load_dataset\n",
        "\n",
        "# Use streaming=True to load the dataset without downloading it fully\n",
        "data = load_dataset(\"MongoDB/cosmopedia-wikihow-chunked\", split=\"train\", streaming=True)\n",
        "# Get first 2k records from the dataset\n",
        "data_head = data.take(2000)\n",
        "df = pd.DataFrame(data_head)\n",
        "\n",
        "# Use this if you want the full dataset\n",
        "# data = load_dataset(\"AIatMongoDB/cosmopedia-wikihow-chunked\", split=\"train\")\n",
        "# df = pd.DataFrame(data)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "70d329bc-cdb7-4651-bef0-8d2ae09d9e4b",
      "metadata": {},
      "source": [
        "## Step 4: Data analysis\n",
        "\n",
        "Make sure the length of the dataset is what we expect (2k), preview the data, drop Nones etc.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 29,
      "id": "39c0f32d-c6f7-4faa-92e1-fae25e9eb2ba",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "2000"
            ]
          },
          "execution_count": 29,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Ensuring length of dataset is what we expect i.e. 2k\n",
        "len(df)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 30,
      "id": "6782ab49-3d9d-4f67-8b33-474f02b7e993",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>doc_id</th>\n",
              "      <th>chunk_id</th>\n",
              "      <th>text_token_length</th>\n",
              "      <th>text</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>180</td>\n",
              "      <td>Title: How to Create and Maintain a Compost Pi...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>141</td>\n",
              "      <td>**Step 2: Gather Materials**\\nGather brown (ca...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>0</td>\n",
              "      <td>2</td>\n",
              "      <td>182</td>\n",
              "      <td>_Key guideline:_ For every volume of green mat...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>0</td>\n",
              "      <td>3</td>\n",
              "      <td>188</td>\n",
              "      <td>_Key tip:_ Chop large items like branches and ...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>0</td>\n",
              "      <td>4</td>\n",
              "      <td>157</td>\n",
              "      <td>**Step 7: Maturation and Use**\\nAfter 3-4 mont...</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "   doc_id  chunk_id  text_token_length  \\\n",
              "0       0         0                180   \n",
              "1       0         1                141   \n",
              "2       0         2                182   \n",
              "3       0         3                188   \n",
              "4       0         4                157   \n",
              "\n",
              "                                                text  \n",
              "0  Title: How to Create and Maintain a Compost Pi...  \n",
              "1  **Step 2: Gather Materials**\\nGather brown (ca...  \n",
              "2  _Key guideline:_ For every volume of green mat...  \n",
              "3  _Key tip:_ Chop large items like branches and ...  \n",
              "4  **Step 7: Maturation and Use**\\nAfter 3-4 mont...  "
            ]
          },
          "execution_count": 30,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Previewing the contents of the data\n",
        "df.head()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 31,
      "id": "04563eaf-bbd8-4969-9671-eb5312817402",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Only keep records where the text field is not null\n",
        "df = df[df[\"text\"].notna()]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 32,
      "id": "cd5a91c3-2f68-4157-a747-05bbc934d53a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "352"
            ]
          },
          "execution_count": 32,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Number of unique documents in the dataset\n",
        "df.doc_id.nunique()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0400259f-65ca-4301-a245-7af0b746abf1",
      "metadata": {},
      "source": [
        "## Step 5: Creating embeddings\n",
        "\n",
        "Define the embedding function, and run a quick test.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 33,
      "id": "3d936743-f18b-410e-8397-c0acf9c61a5e",
      "metadata": {},
      "outputs": [],
      "source": [
        "from typing import List"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 34,
      "id": "bda20d74-7296-40df-ab19-ea63a5b47e6d",
      "metadata": {},
      "outputs": [],
      "source": [
        "def get_embeddings(text: str) -> List[float]:\n",
        "    \"\"\"\n",
        "    Get embeddings using the Gemini API.\n",
        "\n",
        "    Args:\n",
        "        text (str): Text to embed\n",
        "\n",
        "    Returns:\n",
        "        List[float]: Embedding vector\n",
        "    \"\"\"\n",
        "    response = gemini_client.models.embed_content(\n",
        "        model=\"gemini-embedding-001\", contents=text\n",
        "    )\n",
        "    return response.embeddings[0].values"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 35,
      "id": "0da5f1da-f4bd-4551-871e-350d44ed0d31",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Generating a test embedding\n",
        "test_gemini_embed = get_embeddings(df.iloc[0][\"text\"])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 36,
      "id": "a3f8cd22-d3e7-45cb-abe1-4993208f1391",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "3072"
            ]
          },
          "execution_count": 36,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Sanity check to make sure embedding dimensions are as expected i.e. 3072\n",
        "len(test_gemini_embed)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b7020c55",
      "metadata": {},
      "source": [
        "## Step 6: Evaluation\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "17d7c15a-8d3e-4680-acf1-a61a5be5c998",
      "metadata": {},
      "source": [
        "### Measuring embedding latency\n",
        "\n",
        "Create a local vector store (list) of embeddings for the entire dataset.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 37,
      "id": "76e0e043-dea1-4fb7-a779-6aeba0c690e4",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "from tqdm.auto import tqdm"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 38,
      "id": "9e0c475e-8f36-4183-997f-c13b2320b280",
      "metadata": {},
      "outputs": [],
      "source": [
        "texts = df[\"text\"].tolist()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 39,
      "id": "501dc5a1-daed-4ae9-a246-b388b0698e22",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "641ad4184c604f5b906846a90c0d7c68",
              "version_major": 2,
              "version_minor": 0
            },
            "text/plain": [
              "  0%|          | 0/2000 [00:00<?, ?it/s]"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "embeddings = []\n",
        "# Generate embeddings\n",
        "for text in tqdm(texts):\n",
        "    embedding = get_embeddings(text)\n",
        "    # Add to the list of embeddings\n",
        "    embeddings.append(np.array(embedding))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3918f00e-b31f-4225-80fd-1761fbf3a3d2",
      "metadata": {},
      "source": [
        "### Measuring retrieval quality\n",
        "\n",
        "- Create embedding for the user query\n",
        "- Get the top 5 most similar documents from the local vector store using cosine similarity as the similarity metric\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "id": "7fa4806b-7311-4516-aea2-a71230c4f571",
      "metadata": {},
      "outputs": [],
      "source": [
        "from sentence_transformers.util import cos_sim"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "id": "ff11c827-5e24-481b-af48-8389b9963bda",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Converting embeddings list to a Numpy array- required to calculate cosine similarity\n",
        "embeddings = np.asarray(embeddings)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "id": "f9d9c773-896b-4098-8234-fe77360820c9",
      "metadata": {},
      "outputs": [],
      "source": [
        "def query(query: str, top_k: int = 3) -> None:\n",
        "    \"\"\"\n",
        "    Query the local vector store for the top 3 most relevant documents.\n",
        "\n",
        "    Args:\n",
        "        query (str): User query\n",
        "        top_k (int, optional): Number of documents to return. Defaults to 3.\n",
        "    \"\"\"\n",
        "    # Generate embedding for the user query\n",
        "    query_emb = np.asarray(get_embeddings(query))\n",
        "    # Calculate cosine similarity\n",
        "    scores = cos_sim(query_emb, embeddings)[0]\n",
        "    # Get indices of the top k records\n",
        "    idxs = np.argsort(-scores)[:top_k]\n",
        "\n",
        "    print(f\"Query: {query}\")\n",
        "    for idx in idxs:\n",
        "        print(f\"Score: {scores[idx]:.4f}\")\n",
        "        print(texts[idx])\n",
        "        print(\"--------\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "id": "ed8ad9ef-67ad-454d-8fa7-65b1e4a35e03",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Query: Give me some tips to improve my mental health.\n",
            "Score: 0.6919\n",
            "Key Tips & Guidelines:\n",
            "\n",
            "* Monitor your inner dialogue and identify any recurring negative thoughts.\n",
            "* Flip the script by reframing those thoughts into more balanced and realistic alternatives. For example, if you think, \"I always mess up,\" try telling yourself, \"I made a mistake, but I can learn from it.\"\n",
            "* Practice affirmations – short, empowering statements that help build confidence and resilience. Repeat them regularly throughout the day.\n",
            "\n",
            "Why it works: Negative self-talk reinforces low self-esteem and pessimism, while positive thinking promotes mental wellbeing and contentment.\n",
            "\n",
            "Step 3: Foster Social Connections\n",
            "Explanation: Humans are social creatures who thrive on connection and support. Building strong relationships with friends, family, and community contributes to feelings of belonging and happiness.\n",
            "\n",
            "Key Tips & Guidelines:\n",
            "--------\n",
            "Score: 0.6789\n",
            "Step 2: Reach Out to Someone Trustworthy\n",
            "Connect with someone who cares about you—a friend, family member, mental health professional, or support group. Talking openly about your struggles can lighten your emotional burden, making it easier to manage. Sharing your feelings may also lead to helpful suggestions and advice from others.\n",
            "\n",
            "Guideline: Make sure to choose someone trustworthy who has shown empathy towards you before. If possible, reach out to more than one person to build a strong support network around you.\n",
            "\n",
            "Step 3: Engage in Physical Activity\n",
            "Exercise releases endorphins, which improve mood and reduce stress levels. Go for a walk, jog, bike ride, swim, or engage in any physical activity that suits your abilities. Exercising regularly can significantly impact overall wellbeing by reducing symptoms of depression and anxiety.\n",
            "\n",
            "Key Tip: Start small - aim for just five minutes of exercise if needed, then gradually increase duration over time. The most important thing is to get started!\n",
            "--------\n",
            "Score: 0.6748\n",
            "### Step 5: Stay Active\n",
            "\n",
            "**Explanation:** Regular exercise is essential for maintaining both physical and mental health. Exercise releases endorphins that boost energy levels, reduce anxiety, and promote better sleep.\n",
            "\n",
            "* **Key Tips:**\n",
            "\t+ Choose exercises that suit your fitness level and preferences, such as yoga, Pilates, dance classes, or bodyweight training routines.\n",
            "\t+ Allocate time for regular walks outside if possible, taking advantage of parks or scenic routes nearby.\n",
            "\t+ Utilize free resources available online, such as workout videos or apps, to guide your routine.\n",
            "\n",
            "### Step 6: Maintain Social Connections\n",
            "\n",
            "**Explanation:** Strong social relationships contribute significantly to emotional well-being. Nurturing connections with friends and family members prevents feelings of isolation and loneliness.\n",
            "--------\n"
          ]
        }
      ],
      "source": [
        "query(\"Give me some tips to improve my mental health.\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "id": "143fcd7a",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Query: Give me some tips for writing good code.\n",
            "Score: 0.7023\n",
            "Title: How to Become a Good Programmer\n",
            "\n",
            "Introduction:\n",
            "Programming is an essential skill in today's digital world. It opens up various opportunities in different industries such as software development, web development, data science, artificial intelligence, and many more. This comprehensive guide will provide you with actionable steps and valuable insights to become a good programmer. By following this tutorial, you'll learn programming fundamentals, best practices, and strategies for continuous improvement.\n",
            "\n",
            "Step 1: Choose Your Programming Language\n",
            "Choosing the right programming language is crucial when starting your coding journey. Key factors include your interests, career goals, and available resources. Some popular choices are Python (general-purpose), JavaScript (web development), Java (enterprise applications), or C# (game development). Research and select one that aligns with your objectives. For beginners, Python and JavaScript are great options due to their simplicity and versatility.\n",
            "--------\n",
            "Score: 0.6997\n",
            "Step 6: Improve Code Quality\n",
            "Strive for clean, readable, maintainable code. Adopt consistent naming conventions, indentation styles, and formatting rules. Utilize version control systems like Git to track changes and collaborate effectively. Leverage linters and static analyzers to enforce style guides automatically. Document your work using comments and dedicated documentation tools. High-quality code facilitates collaboration, promotes longevity, and simplifies troubleshooting.\n",
            "\n",
            "Step 7: Embrace Best Practices\n",
            "Follow established best practices relevant to your chosen language and domain. Examples include Object-Oriented Design Principles, SOLID principles, Test-Driven Development (TDD), Dependency Injection, Asynchronous Programming, etc. While seemingly overwhelming initially, integrating them gradually enhances design patterns, scalability, and extensibility. Consult authoritative blogs, books, and articles to stay updated on current trends and recommendations.\n",
            "--------\n",
            "Score: 0.6727\n",
            "Conclusion:\n",
            "Becoming a good programmer requires dedication, persistence, and patience. By methodically progressing through these steps, mastering core concepts, practicing diligently, engaging with peers, and committing to continuous improvement, you'll be well on your way to achieving your goal. Remember, every expert was once a beginner - keep pushing forward!\n",
            "--------\n"
          ]
        }
      ],
      "source": [
        "query_emb = query(\"Give me some tips for writing good code.\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 23,
      "id": "6fd44daa",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Query: How do I create a basic webpage?\n",
            "Score: 0.6636\n",
            "Step 6: Choose a Template\n",
            "After logging in, select a template that suits your preferences by browsing through various categories such as business, personal, blog, etc., located on the left sidebar under \"Template Categories\". Once you find a suitable design, hover over it and click on the green \"Use this template\" button below the preview image.\n",
            "\n",
            "Step 7: Customize Your Site\n",
            "You can customize different aspects of your site like its layout, color scheme, background image, font styles, and more via the editor dashboard on the left panel. Remember to save changes made before navigating away from any editing screen.\n",
            "\n",
            "Step 8: Add Pages\n",
            "To add pages to your website, go to the \"Pages\" tab on the editor dashboard. Here, choose between predefined page types (e.g., Home, About Us, Services) or create custom ones according to your requirements. Don't forget to assign appropriate titles and URL slugs to these pages.\n",
            "--------\n",
            "Score: 0.6482\n",
            "Step 9: Edit Page Content\n",
            "For each added page, utilize the content editor to input text, images, videos, links, tables, dividers, or other elements needed. Format texts using headings, bullet points, numbered lists, indentation, alignment, and colors as necessary.\n",
            "\n",
            "Step 10: Configure Settings\n",
            "Navigate to the \"Settings\" tab on the editor dashboard. Fill in essential details about your site including name, description, keywords, contact info, social media profiles, analytics tracking codes, and SEO settings. Save changes once completed.\n",
            "\n",
            "Step 11: Preview Your Site\n",
            "Before publishing your site, preview it first by clicking on the eye icon near the top right corner of the editor interface. Review your entire site carefully, checking for errors or inconsistencies. If satisfied, proceed to the next step; otherwise, make adjustments accordingly.\n",
            "--------\n",
            "Score: 0.6396\n",
            "Step 12: Publish Your Site\n",
            "Once everything is set up correctly, hit the orange \"Publish\" button located at the upper right corner of the editor interface. Confirm publication when prompted. Congratulations! Your free website is now live on the internet.\n",
            "\n",
            "Key Tips & Guidelines:\n",
            "\n",
            "* Always remember to save changes after making edits.\n",
            "* Use descriptive titles and URL slugs for better search engine optimization (SEO).\n",
            "* Utilize header tags (H1, H2, etc.) appropriately for improved readability and ranking.\n",
            "* Optimize visual content by compressing large files and adding alt attributes.\n",
            "* Regularly update your site with fresh content to maintain user engagement and improve rankings.\n",
            "--------\n"
          ]
        }
      ],
      "source": [
        "query(\"How do I create a basic webpage?\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 24,
      "id": "ce25fee3",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Query: What are some environment-friendly practices I can incorporate in everyday life?\n",
            "Score: 0.7323\n",
            "Title: How to Save Our Environment: A Comprehensive Guide\n",
            "\n",
            "Introduction:\n",
            "The environment is the foundation of all life on Earth. It provides us with air to breathe, water to drink, food to eat, and countless other resources that are essential for our survival. However, human activities have led to severe environmental degradation, including climate change, deforestation, pollution, and loss of biodiversity. To ensure a sustainable future for ourselves and generations to come, we must take action now to save our environment. This comprehensive guide offers practical steps you can take to reduce your impact on the planet and contribute to global efforts towards sustainability.\n",
            "\n",
            "Step 1: Reduce Your Carbon Footprint\n",
            "A carbon footprint refers to the total greenhouse gas emissions produced directly or indirectly by an individual, organization, event, or product. By reducing your carbon footprint, you help mitigate climate change and its devastating impacts on ecosystems and communities worldwide. Here's how:\n",
            "--------\n",
            "Score: 0.7112\n",
            "a) Use public transportation, carpool, bike, walk, or telecommute whenever possible to minimize fuel consumption.\n",
            "b) If purchasing a vehicle, consider electric or hybrid options that emit fewer greenhouse gases than traditional gasoline-powered cars.\n",
            "c) Improve home energy efficiency through insulation, LED lighting, Energy Star appliances, and renewable energy sources like solar panels.\n",
            "d) Limit air travel and opt for video conferencing when feasible.\n",
            "e) Be mindful of your dietary choices – consume less red meat, choose locally sourced foods, and reduce food waste.\n",
            "f) Plant trees and support reforestation projects as they absorb CO2 from the atmosphere.\n",
            "g) Advocate for policies that promote clean energy and reduced emissions at local, national, and international levels.\n",
            "\n",
            "Key Tip: Calculate your carbon footprint using online tools (such as the EPA's Household Carbon Footprint Calculator) to identify areas where you can make improvements.\n",
            "--------\n",
            "Score: 0.7055\n",
            "Step 2: Conserve Water\n",
            "Freshwater scarcity is becoming increasingly prevalent due to population growth, urbanization, agricultural practices, and climate change. Follow these strategies to conserve water:\n",
            "\n",
            "a) Fix leaks promptly and install low-flow faucets, showerheads, and dual-flush toilets.\n",
            "b) Only run full loads in washing machines and dishwashers.\n",
            "c) Collect rainwater for irrigation purposes and use drought-resistant plants in landscaping.\n",
            "d) Avoid hosing down driveways and sidewalks; instead, sweep debris away.\n",
            "e) Support policies promoting efficient water use and protecting watersheds.\n",
            "\n",
            "Key Guideline: The average American uses about 80-100 gallons of water per day. Strive to reduce this amount through conscious conservation efforts.\n",
            "\n",
            "Step 3: Minimize Waste and Recycle\n",
            "Reducing waste production conserves natural resources, prevents pollution, and reduces strain on landfill capacity. Implement these measures:\n",
            "--------\n"
          ]
        }
      ],
      "source": [
        "query(\n",
        "    \"What are some environment-friendly practices I can incorporate in everyday life?\"\n",
        ")"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "conda_python3",
      "language": "python",
      "name": "conda_python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.18"
    },
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "state": {}
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
